package co.fitstart.market.web.controller.questionnaire;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.wechat.web.interceptor.WechatJsConfig;

import co.fitstart.entity.market.MarketCourseRound;
import co.fitstart.entity.market.MarketInvitationRecord;
import co.fitstart.entity.market.MarketMonthlyCourseware;
import co.fitstart.entity.market.MarketRecommendRecord;
import co.fitstart.entity.market.ParticipationQrcode;
import co.fitstart.entity.market.Questionnaire;
import co.fitstart.entity.user.User;
import co.fitstart.market.service.CoursewareService;
import co.fitstart.market.service.DataService;
import co.fitstart.market.service.MarketCourseRoundService;
import co.fitstart.market.service.MarketInvitationRecordService;
import co.fitstart.market.service.ParticipationService;
import co.fitstart.market.service.QrcodeService;
import co.fitstart.market.service.QuestionnaireService;
import co.fitstart.market.service.UserService;
import co.fitstart.market.web.interceptor.Router;
import co.fitstart.market.web.interceptor.WechatAuthority;

/**
 * 
 * @author dan
 *
 */
@Controller
@RequestMapping("/questionnaires")
public class QuestionnaireController {
    
    @Autowired
    private MarketInvitationRecordService marketInvitationRecordService;
    
    @Autowired
    @Qualifier("dataService")
    private DataService<MarketRecommendRecord> marketRecommendRecordService;
    
    @Autowired
    private QuestionnaireService questionnaireService;
    
    @Autowired
    private MarketCourseRoundService marketCourseRoundService;
    
    @Autowired
    private CoursewareService coursewareService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private ParticipationService participationService;
    
    @Autowired
    private QrcodeService qrcodeService;
    
    /**
     * 
     * @param openid
     * @param inviter
     * @param recommenderOpenid
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @Router(targetUrl = "/required-wechat")
    @WechatAuthority
    public ModelAndView index(@CookieValue(name = "fitstart_test_openid", required = true) String openid,
                              @RequestParam(name = "inviter", required = false) String inviter,
                              @RequestParam(name = "recommender", required = false) String recommenderOpenid) {
        ModelAndView modelAndView = new ModelAndView("questionnaire/questionnaire-index");
        
        // 如果有邀请人，保存邀请人记录
        if(StringUtils.isNoneEmpty(inviter)) {
            marketInvitationRecordService.create(inviter, openid);
        } else if(StringUtils.isNoneEmpty(recommenderOpenid)) {
            marketRecommendRecordService.save(new MarketRecommendRecord(recommenderOpenid, openid));
        }
        
        User user = userService.getUserByOpenId(openid);
        if(user != null) {
            MarketCourseRound courseRound = marketCourseRoundService.load(user);
            if(courseRound != null) {
                modelAndView.setViewName("redirect:/questionnaires/result");
            }
        }
        
        return modelAndView;
    }
    
    /**
     * 
     * @param openid
     * @return
     */
    @RequestMapping(value = "/check", method = RequestMethod.GET)
    @Router(targetUrl = "/required-wechat")
    @WechatAuthority
    public ModelAndView check(@CookieValue(name = "fitstart_test_openid", required = true) String openid) {
        ModelAndView modelAndView = new ModelAndView("questionnaire/questionnaire-check");
        
        User user = userService.getUserByOpenId(openid);
        if(user != null) {
            MarketCourseRound courseRound = marketCourseRoundService.load(user);
            if(courseRound != null) {
                modelAndView.setViewName("redirect:/questionnaires/result");
            }
        }
        
        return modelAndView;
    }
    
    /**
     * 
     * @param openid
     * @return
     */
    @RequestMapping(value = "/result", method = RequestMethod.GET)
    @Router(targetUrl = "/required-wechat")
    @WechatAuthority
    @WechatJsConfig
    public ModelAndView result(@CookieValue(name = "fitstart_test_openid", required = true) String openid) {
        ModelAndView modelAndView = new ModelAndView("questionnaire/questionnaire-result");
        
        User user = userService.getUserByOpenId(openid);
        if(user == null) {
            modelAndView.setViewName("questionnaire/register");
            String url = "/questionnaires/result";
            modelAndView.addObject("currentUrl", url);
        } else {
            MarketCourseRound courseRound = marketCourseRoundService.load(user);
            
            // if courseRound is null redirect to participateUrl
            if(courseRound == null) {
                modelAndView.setViewName("redirect:/participation/participate");
            } else {
                
                Questionnaire questionnaire = questionnaireService.load(openid);
                modelAndView.addObject("questionnaire", questionnaire);
                
                List<MarketMonthlyCourseware> monthlyCoursewares = coursewareService.listMonthlyCourseware(courseRound);
                modelAndView.addObject("monthlyCoursewares", monthlyCoursewares);
                
                List<MarketInvitationRecord> invitationRecords = marketInvitationRecordService.list(user.getOpenid());
                modelAndView.addObject("invitees", invitationRecords.size());
                
                modelAndView.addObject("course", courseRound.getCourse());
                
                modelAndView.addObject("user", user);
                
            }
        }
        
        return modelAndView;
    }
    
    /**
     * 
     * @param openid
     * @return
     */
    @RequestMapping(value = "/result-share", method = RequestMethod.GET)
    @Router(targetUrl = "/required-wechat")
    @WechatAuthority
    public ModelAndView share(@RequestParam("inviter") String openid) {
        ModelAndView modelAndView = new ModelAndView("questionnaire/questionnaire-result-share");
        
        User inviter = userService.getUserByOpenId(openid);
        
        MarketCourseRound courseRound = marketCourseRoundService.load(inviter);
        
        Questionnaire questionnaire = questionnaireService.load(openid);
        modelAndView.addObject("questionnaire", questionnaire);
        
        List<MarketMonthlyCourseware> monthlyCoursewares = coursewareService.listMonthlyCourseware(courseRound);
        modelAndView.addObject("monthlyCoursewares", monthlyCoursewares);
        
        modelAndView.addObject("course", courseRound.getCourse());
        
        ParticipationQrcode participationQrcode = participationService.loadParticipationQrcode(false, inviter);
        String qrcode = null;
        if(participationQrcode == null) {
            qrcode = qrcodeService.generateQrcode(false, inviter);
        } else {
            qrcode = participationQrcode.getQrcode();
        }
        modelAndView.addObject("qrcode", qrcode);
        
        
        return modelAndView;
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    @Router(targetUrl = "/required-wechat")
    @WechatAuthority
    @WechatJsConfig
    public ModelAndView register() {
    	ModelAndView modelAndView = new ModelAndView("questionnaire/register");
        String url = "/questionnaires/result";
        modelAndView.addObject("currentUrl", url);
        return modelAndView;
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/email-register", method = RequestMethod.GET)
    @Router(targetUrl = "/required-wechat")
    @WechatAuthority
    @WechatJsConfig
    public ModelAndView emailRegister() {
    	ModelAndView modelAndView = new ModelAndView("questionnaire/email-register");
        String url = "/questionnaires/result";
        modelAndView.addObject("currentUrl", url);
        return modelAndView;
    }
    
}
